package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
//    @Async
//    @Scheduled(cron = "0 * * * * ? ")
    @XxlJob("processTimeoutOrders")
    public void processTimeoutOrders(){
        log.info("[处理超时订单]定时任务执行开始: {}", LocalDateTime.now());

        // 查询创建时间在15分钟前并且待支付状态的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (!CollectionUtils.isEmpty(ordersList)) {

            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
        log.info("[处理超时订单]定时任务执行结束: {}", LocalDateTime.now());
    }

    /**
     * 处理派送中订单
     */
//    @Async
//    @Scheduled(cron = "0 0 1 * * ? ")
    @XxlJob("processDeliveryOrder")
    public void processDeliveryOrder() {
        log.info("[处理派送中订单]定时任务执行开始: {}", LocalDateTime.now());

        // 查询创建时间在15分钟前并且待支付状态的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (!CollectionUtils.isEmpty(ordersList)) {

            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
        log.info("[处理派送中订单]定时任务执行结束: {}", LocalDateTime.now());
    }

}
